package cn.actoncode.boot.module.ai.service.chatmodel.impl;

import cn.actoncode.boot.framework.common.exception.ServiceException;
import cn.actoncode.boot.module.ai.service.chatmodel.ChatStrategyService;
import cn.actoncode.boot.module.ai.service.chatmodel.dto.ChatHistoryDTO;
import cn.actoncode.boot.module.ai.service.chatmodel.dto.ChatRespDTO;
import cn.actoncode.boot.module.ai.socket.chat.ChatSocket;
import com.vdurmont.emoji.EmojiParser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.List;

import static cn.actoncode.boot.framework.common.exception.enums.GlobalErrorCodeConstants.NLP_ERROR;
import static cn.actoncode.boot.framework.common.exception.util.ServiceExceptionUtil.exception;

@Slf4j
public abstract class AbstractChatServiceImpl implements ChatStrategyService {

    @Resource
    private ChatSocket chatSocket;

    public ChatRespDTO chat(String prompt, List<ChatHistoryDTO> historyList, String system, Boolean stream, String userId, Long sk) {
        try {
            return doChat(prompt, historyList, system, stream, userId, sk);
        } catch (ServiceException e) {
            log.info("ChatError : {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            throw exception(NLP_ERROR, "当前功能使用人数过多，请稍后再试");
        }
    }

    protected void sendMessage(Long sk, String message) {
        chatSocket.sendMessage(sk, EmojiParser.parseToUnicode(message));
    }

    protected void sendMessage(Long sk, boolean incremental) {
        if (incremental) {
            chatSocket.sendMessage(sk, "INCREMENTAL_TRUE");
        } else {
            chatSocket.sendMessage(sk, "INCREMENTAL_FALSE");
        }
    }

    protected abstract ChatRespDTO doChat(String prompt, List<ChatHistoryDTO> historyList, String system, Boolean stream, String userId, Long sk);

    protected abstract <T> T sendMessage(Long sk, InputStream inputStream);
}
